<?php

namespace admin\widgets;

use admin\assets\EditorAsset;
use yii\db\JsonExpression;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\JsExpression;
use yii\widgets\InputWidget;

class EditorWidget extends InputWidget {

    public $editSetting = [];

    public function init() {
        parent::init();
        if (!isset($this->Setting['class'])) {
            $this->options['class'] = 'form-control';
        }
    }

    public function run() {
        $this->registerClientScript();

        if ($this->hasModel()) {
            $input = Html::activeTextarea($this->model, $this->attribute, $this->options);
        } else {
            $input = Html::textarea($this->name, $this->value, $this->options);
        }
        echo $input;
    }

    protected function registerClientScript() {
        $options = $this->defaults();

        $id = Html::getInputId($this->model, $this->attribute);
        $options = ArrayHelper::merge($options, $this->editSetting);
        $options = Json::htmlEncode($options);

        $view = $this->getView();
        EditorAsset::register($view);

        $view->registerJs("$(document).ready(function(){window.editor = \$('#{$id}').summernote({$options});});");
    }

    private function defaults() {
        $uploadUrl = Url::to(['upload']);
        $onImageUpload = "function(files){App.upload(files, '$uploadUrl', $(this))}";
        return [
            'lang' => 'zh-CN',
            'height' => 300,
            'toolbar' => [
                ['style', ['bold', 'italic', 'underline', 'strikethrough', 'fontname', 'fontsize', 'color']],
//                ['font', ['strikethrough', 'superscript', 'subscript']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['insert', ['hr', 'link', 'picture', 'table']],
                ['misc', ['codeview', 'clear', 'more', 'fullscreen']]
            ],
            'buttons' => ['more' => new JsExpression('MoreButton')],
            'callbacks' => [
                'onImageUpload' => new JsExpression($onImageUpload)
            ]
        ];
    }
}